<?php

namespace App\Repositories;


use App\Models\LoginLog;
use App\Models\User;
use App\Utils\Output;
use App\Utils\Pager;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

/**
 * Class UserRepository
 * @package App\Repositories
 */
class UserRepository
{
    function adminPager($params)
    {
        extract($params);
        $query = User::query();
        if (!empty($keyword)) {
            $query->where(function (Builder $q) use ($keyword) {
                $q->where('users.username', 'like', "%$keyword%");
                $q->orWhere('users.name', 'like', "%$keyword%");
                $q->orWhere('users.mobile', 'like', "%$keyword%");
            });
        }
        if (!empty($start)) {
            $query->where('users.created_at', '>=', strtotime($start));
        }
        if (!empty($end)) {
            $query->where('users.created_at', '<=', strtotime($end . ' 23:59:59'));
        }
        if (!empty($role_tag)) {
            $query->where('users.role_tag', '=', $role_tag);
        }
        if (!empty($status)) {
            $query->where('users.status', '=', $status);
        }
        if (!empty($group)) {
            $query->where('users.role_tag', 'like', $group . '%');
        }

        $query->leftJoin('roles', 'roles.tag', 'users.role_tag');
        $query->select(
            'users.id',
            'users.username',
            'roles.name as role_name',
            'users.name',
            'users.mobile',
            'users.status',
            'users.status as status_text',
            'users.updated_at'
        );
        return $query->paginate();
    }

    function editInfo($id)
    {
        $entity = User::find($id);
        if ($entity) {
            return Output::data($entity);
        }
        return Output::fail("数据不存在");
    }


    /**
     * 删除
     * @param $id
     * @return Output|int
     * @throws \Exception
     */
    function destroy($id)
    {
        if ($id == 1) {
            return Output::fail("超级管理员不能删除！");
        }
        return User::destroy($id);
    }

    function changeSkin($id, $skin)
    {
        User::query()->where('id', '=', $id)->update(['skin' => $skin]);
    }

    /**
     * @param $id
     * @param $status
     * @return Output
     */
    function changeStatus($id, $status)
    {
        if ($id == 1) {
            return Output::fail("不能修改超级管理员状态！");
        }
        $entity = User::find($id);
        if ($entity) {
            $entity->status = $status == 1 ? 1 : 2;
            $entity->save();
            return Output::success('操作成功');
        }
        return Output::fail("数据不存在");
    }

    /**
     * @param $data
     * @param int $id
     * @return Output
     */
    function save($data, $id = 0)
    {
        if ($id) {
            $entity = User::find($id);
            if (empty($entity)) {
                return Output::fail('数据不存在');
            }
        } else {
            $entity = new User();
        }
        $entity->fill($data);
        if (!$id) {
            return $this->_setPassword($entity, Arr::get($data, 'password'));
        } else {
            $entity->save();
        }
        return Output::success('操作成功');
    }

    /**
     * @param $id
     * @param $old
     * @param $pass
     * @return Output
     */
    function changePassword($id, $old, $pass)
    {
        $userInfo = User::find($id);
        if ($userInfo) {
            if ($userInfo->password == $this->_buildPassword($old, $userInfo->salt)) {
                return $this->_setPassword($userInfo, $pass);
            } else {
                return Output::fail('密码错误！');
            }
        }
        return Output::fail('用户不存在！');
    }

    /**
     * @param User $userInfo
     * @param $pass
     * @return Output
     */
    function _setPassword($userInfo, $pass)
    {
        $userInfo->salt = Str::random(4);
        $userInfo->password = $this->_buildPassword($pass, $userInfo->salt);
        $userInfo->save();
        return Output::success('操作成功');
    }

    function setPassword($id, $pass)
    {
        $userInfo = User::find($id);
        if ($userInfo) {
            return $this->_setPassword($userInfo, $pass);
        }
        return Output::fail('用户不存在！');
    }

    private function _buildPassword($pass, $salt)
    {
        return md5(md5($pass) . $salt);
    }

    function login($username, $password, $role_tag = '')
    {
        $query = User::query()
            ->where('username', '=', $username);
        if (!empty($role_tag)) {
            if (is_array($role_tag)) {
                $query->whereIn('role_tag', $role_tag);
            } else {
                $query->where('role_tag', '=', $role_tag);
            }
        }
        $userInfo = $query->first();
        if ($userInfo) {
            if ($userInfo->status != 1) {
                return Output::fail('账号已被冻结！');
            }
            if ($userInfo->password == $this->_buildPassword($password, $userInfo->salt)) {
                unset($userInfo->salt);
                unset($userInfo->password);
                //添加登录日志
                LoginLog::create([
                    'ip' => request()->ip(),
                    'client' => 1,
                    'user_id' => $userInfo->id,
                    'desc' => '账号密码登录'
                ]);
                return Output::data($userInfo->toArray());
            } else {
                return Output::fail('密码错误！');
            }
        }
        return Output::fail('用户不存在！');
    }

    function saleLogin($mobile, $password, $role_tag = '')
    {
        $query = User::query()
            ->where('mobile', '=', $mobile);
        if (!empty($role_tag)) {
            if (is_array($role_tag)) {
                $query->whereIn('role_tag', $role_tag);
            } else {
                $query->where('role_tag', '=', $role_tag);
            }
        }
        $userInfo = $query->first();
        if ($userInfo) {
            if ($userInfo->status != 1) {
                return Output::fail('账号已被冻结！');
            }
            if ($userInfo->password == $this->_buildPassword($password, $userInfo->salt)) {
                return Output::data($userInfo);
            } else {
                return Output::fail('密码错误！');
            }
        }
        return Output::fail('用户不存在！');
    }
}

